﻿/// <reference path = "Base.ts" />
namespace VantCellTypes {

    interface UploadCellTypeParam {
        maxCount: number;
        accept: string;
        maxSize: number;
        capture: "images" | "camera";
        showUpload: boolean;
        uploadIcon: Icon;
        uploadText: string;
        previewSize: number;
        imageFit: string;
        previewFullImage: boolean;
        deletable: boolean;
        multiple: boolean;
        IsDisabled: boolean;
        ReadOnly: boolean;
        OverFileSizeLimitError: string;
        UnacceptableFileError: string;
        UploadImageLimit: Forguncy.UploadImageLimit;
    }

    export class UploadCellType extends VantCellTypeBase<UploadCellTypeParam> {
        public onPageLoaded(info: Forguncy.Plugin.CellTypeInfo) {
            const self = this;
            const cellType = this.cellType;
            
            const option = {
                template: `
<van-uploader
    v-model="fileList"
    :max-count="maxCount"
    :accept="accept"
    :max-size="maxSize * 1024 * 1024"
    :capture="capture"
    :show-upload="showUpload && !readonly"
    :upload-icon="uploadIcon"
    :upload-text="uploadText"
    :preview-size="previewSize"
    :image-fit="imageFit"
    :preview-image="true"
    :preview-full-image="previewFullImage && !disabled"
    :deletable="deletable && !readonly && !disabled"
    :multiple="multiple"
    :readonly="readonly"
    :disabled="disabled"
    :before-read="checkExtension"
    :after-read="uploadFile"
    @oversize="handleOversize"
    @delete="handleDelete"
>
</van-uploader>
`,
                data() {
                    return {
                        fileList: [],
                        maxCount: cellType.maxCount || Infinity,
                        accept: cellType.capture === "images" ? cellType.accept : undefined,
                        maxSize: cellType.maxSize || Infinity,
                        capture: cellType.capture === "images" ? undefined : cellType.capture,
                        showUpload: !!cellType.showUpload,
                        uploadIcon: undefined,
                        uploadText: cellType.uploadText,
                        previewSize: cellType.previewSize,
                        imageFit: cellType.imageFit,
                        previewFullImage: !!cellType.previewFullImage,
                        deletable: !!cellType.deletable,
                        multiple: !!cellType.multiple,
                        readonly: false,
                        disabled: false
                    };
                },
                methods: {
                    getValue() {
                        const fileNameList = this.fileList.map(file => file?.fgc_fileName);
                        return fileNameList.filter(name => !self.isEmpty(name)).join("|");
                    },
                    setValue(value: string) {
                        if (value === this.getValue()) {
                            return;
                        }
                        if (typeof value !== "string" || self.isEmpty(value)) {
                            this.fileList = [];
                        } else {
                            const values = value.split("|").filter(item => !self.isEmpty(item));
                            this.fileList = values.map((fgcFileName: string) => {
                                if (fgcFileName && fgcFileName.length > 37 && fgcFileName.charAt(36) === "_") {
                                    return {
                                        fgc_fileName: fgcFileName,
                                        url: UploadCellType.getFileUrl(fgcFileName)
                                    };
                                }
                            }).filter(item => !self.isEmpty(item));
                        }
                    },
                    setReadOnly(value: boolean) {
                        this.readonly = value;
                    },
                    disable() {
                        this.disabled = true;
                    },
                    enable() {
                        this.disabled = false;
                    },
                    uploadFile(data) {
                        const successCallback = (fileName) => {
                            data.fgc_fileName = fileName;
                            data.url = UploadCellType.getFileUrl(fileName);
                            data.status = "";
                            self.commitValue();
                        };
                        const errorCallback = () => {
                            data.status = 'failed';
                            self.commitValue();
                        };
                        if (UploadCellType.isImage(data.file.name)) {
                            Forguncy.Common.uploadImageToServer(data.file, cellType.UploadImageLimit, this.accept, successCallback, errorCallback);
                        } else {
                            Forguncy.Common.uploadFileByHTML5(data.file, successCallback, errorCallback, null, self.CellElement.ServerPropertiesId.UploadLimit);
                        }
                    },
                    checkExtension(file) {
                        if (cellType.accept) {
                            const exts = cellType.accept.split(",").filter(i => i).map(i => i.trim());
                            if (!exts.some(i => file.name.endsWith(i))) {
                                this.$notify(cellType.UnacceptableFileError);
                                return false;
                            }
                        }
                        return true;
                    },
                    handleOversize() {
                        this.$notify(cellType.OverFileSizeLimitError);
                    },
                    handleDelete() {
                        self.commitValue();
                    },
                    downloadNonImageFile(index: number) {
                        const data = this.fileList[index];
                        if (this.disabled || data.status === "failed" || UploadCellType.isImage(data.fgc_fileName)) {
                            return;
                        }
                        Forguncy.Common.download(data.url);
                    }
                },
                updated() {
                    const previewItems = $(".van-uploader__preview", this.$el);

                    for (let i = 0; i < previewItems.length; i++) {
                        const el = previewItems[i];
                        const NonImageItem = $(el).find(".van-uploader__file")[0];
                        if (NonImageItem) {
                            NonImageItem.onclick = null;
                        }
                    }

                    for (let i = 0; i < previewItems.length; i++) {
                        const el = previewItems[i];
                        const NonImageItem = $(el).find(".van-uploader__file")[0];
                        if (NonImageItem) {
                            NonImageItem.onclick = e => this.downloadNonImageFile(i);
                        }
                    }
                }
            };

            this.createVueApp(option);

            IconHelper.getIcon(cellType.uploadIcon, icon => {
                this.vue.uploadIcon = icon;
            });

            super.onPageLoaded(info);
        }

        static getFileUrl(fileName: string) {
            const root = Forguncy.Helper.SpecialPath.getBaseUrl();
            return root + Forguncy.ModuleLoader.getCdnUrl("FileDownloadUpload/Download?file=" + encodeURIComponent(fileName));
        }
        static isImage(fileName: string) {
            if (fileName) {
                const pointIndex = fileName.lastIndexOf(".");
                if (pointIndex) {
                    const extension = fileName.toLowerCase().substring(pointIndex + 1, fileName.length);
                    return ["jpg", "jpeg", "png", "gif", "eps", "svg", "bmp", "tif", "tiff"].some(i => i === extension);
                }
            }
            return false;
        }
    }
}

Forguncy.Plugin.CellTypeHelper.registerCellType("Vant.CellTypes.Upload, Vant", VantCellTypes.UploadCellType);